<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use App\Models\Dept;
use App\Models\Notice;
use DateTimeInterface;


class User extends Authenticatable implements JWTSubject
{

    use HasFactory, Notifiable;

    const CREATED_AT = 'createTime';
    const UPDATED_AT = 'updateTime';

    protected $fillable = [
        'username',
        'password',
        'nickname',
        'avatar',
        'mobile',
        'status',
        'deptId',
        'email',
        'gender',
        'roleIds',
    ];

    protected $hidden = [
        'password',
    ];

    protected function casts(): array
    {
        return [
            'roleIds' => 'json'
        ];
    }

    public function dept()
    {
        // 用户属于一个部门
        return $this->belongsTo(Dept::class, 'deptId');
    }

    protected function serializeDate(DateTimeInterface $date): string
    {
        /** @var \Carbon\Carbon $date */
        return $date->timezone('Asia/Shanghai')->format('Y-m-d H:i:s');
    }

    // 所有关于用户的通知
    public function notices()
    {
        return $this->belongsToMany(Notice::class, 'notice_user')->withPivot('is_read');
    }

    // 已读通知
    public function readNotices()
    {
        return $this->notices()->wherePivot('is_read', 1);
    }

    // 未读通知
    public function unreadNotices()
    {
        return $this->notices()->wherePivot('is_read', 0);
    }

    function getJWTIdentifier()
    {
        return $this->getKey();
    }

    function getJWTCustomClaims()
    {
        return [];
    }
}
